<script lang="ts" setup>
import type { AiFormVariablesApi } from '#/api/ai/form/formVariables';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  createFormVariables,
  updateFormVariables,
} from '#/api/ai/form/formVariables';
import { $t } from '#/locales';

import { FormDesignFormSchema } from '../data';

const emit = defineEmits(['success']);
const formData = ref<AiFormVariablesApi.FormVariables>();
const getTitle = computed(() => {
  return formData.value?.id
    ? $t('ui.actionTitle.edit', ['提示词变量'])
    : $t('ui.actionTitle.create', ['提示词变量']);
});

const formId = ref(null);

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    labelWidth: 100,
  },
  wrapperClass: 'grid-cols-1',
  layout: 'horizontal',
  schema: FormDesignFormSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    // 提交表单
    const data =
      (await formApi.getValues()) as AiFormVariablesApi.FormVariables;
    const isCustomOptions = data.metadata?.isCustomOptions ?? false;
    let newData = {};
    if (
      (data.htmlType === 'select' ||
        data.htmlType === 'radio' ||
        data.htmlType === 'checkbox') &&
      isCustomOptions
    ) {
      let dictOptionsList = [];
      dictOptionsList =
        data.metadata?.dictOptions &&
        typeof data.metadata?.dictOptions === 'string'
          ? JSON.parse(data.metadata?.dictOptions)
          : data.metadata?.dictOptions || [];
      if (dictOptionsList.length > 0) {
        const dictOptions = [];
        dictOptionsList.forEach((item) => {
          if (item.label) {
            dictOptions.push({
              label: item.label,
              value: item.value ?? item.label,
            });
          }
        });
        if (dictOptions.length > 0) {
          // 判断数据字典选择value和label是否有重复
          const valueSet = new Set(dictOptions.map((item) => item.value));
          const labelSet = new Set(dictOptions.map((item) => item.label));
          if (
            valueSet.size !== dictOptions.length ||
            labelSet.size !== dictOptions.length
          ) {
            message.warn('数据字典选项value和label不能重复');
            return;
          }
        } else {
          message.warn('请添加数据字典选项');
          return;
        }
        // 赋值
        const metadata = { ...data.metadata, dictOptions };
        newData = { ...data, metadata: JSON.stringify(metadata) };
      } else {
        message.warn('请添加数据字典选项');
        return;
      }
    } else {
      const metadata = { ...data.metadata };
      newData = { ...data, metadata: JSON.stringify(metadata) };
    }

    // 假设 data 是整个表单数据
    if (
      data.htmlType === 'apiSelect' ||
      data.htmlType === 'apiPagingSelect' ||
      data.htmlType === 'selectTree' ||
      data.htmlType === 'autoComplete' ||
      data.htmlType === 'apiCascader'
    ) {
      let apiParamsList: DictOption[] = [];
      const raw = data.metadata?.apiParams;

      // JSON 字符串或数组
      if (raw) {
        apiParamsList = typeof raw === 'string' ? JSON.parse(raw) : raw;
      }

      // 校验 paramKey 重复
      const keySet = new Set<string>();
      for (const item of apiParamsList) {
        if (!item.paramKey) {
          message.warn('参数名不能为空');
          return;
        }
        if (keySet.has(item.paramKey)) {
          message.warn(`参数名 ${item.paramKey} 不能重复`);
          return;
        }
        keySet.add(item.paramKey);
      }

      // 校验 sourceType 和 value
      for (const item of apiParamsList) {
        if (!item.sourceType) {
          message.warn(`参数 ${item.paramKey} 来源不能为空`);
          return;
        }
        if (!item.value) {
          message.warn(`参数 ${item.paramKey} 值不能为空`);
          return;
        }
      }

      // 最终赋值
      const metadata = { ...data.metadata, apiParams: apiParamsList };
      newData = { ...data, metadata: JSON.stringify(metadata) };
      // 这里 newData 就是可以提交的表单数据
    } else {
      // 非接口相关类型
      const metadata = { ...data.metadata };
      newData = { ...data, metadata: JSON.stringify(metadata) };
    }

    if (newData.metadata && typeof newData.metadata === 'string') {
      newData.metadata = JSON.parse(newData.metadata);
    }

    newData.formId = formId.value;

    await (formData.value?.id
      ? updateFormVariables(newData)
      : createFormVariables(newData));
    // 关闭并提示
    await modalApi.close();
    emit('success');
    message.success($t('ui.actionMessage.operationSuccess'));
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      return;
    }

    // 获取主界面传入的数据
    const data = modalApi.getData<AiFormVariablesApi.FormVariables>();

    formId.value = data.formId;

    // 处理 tableData 生成 formFieldList
    const formFieldList = (data.tableData || []).map((item: any) => ({
      label: item.name,
      field: item.displayName,
    }));

    // 解析 metadata
    if (data.metadata && typeof data.metadata === 'string') {
      data.metadata = JSON.parse(data.metadata);
    }

    if (!data.metadata) data.metadata = {};

    // 把生成的 formFieldList 放到 metadata 下
    data.formFieldList = JSON.stringify(formFieldList || []);

    formData.value = data;

    // 设置到表单
    await formApi.setValues(data);
  },
});
</script>

<template>
  <Modal :title="getTitle" class="w-[60%]">
    <Form class="mx-4" />
  </Modal>
</template>
